﻿using System;
using System.Web.Mvc;
using Ornament.Messages;
using Ornament.Messages.Dao;
using Ornament.Web;
using Ornament.Web.Mvc;

namespace Ornament.MVCWebFrame.Areas.Infos.Controllers
{
    public class TypeController : Controller
    {
        //
        // GET: /Infos/Type/

        public ActionResult Index()
        {
            ViewData["types"] = OrnamentContext.Current.MessageManager.Factory.InfoTypeDao.GetFirstLevel();
            return View();
        }

        [JsonContainerFilter, AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(JsonContainer type)
        {
            IInfoTypeDao dao = OrnamentContext.Current.MessageManager.Factory.InfoTypeDao;
            InfoType info = type.Contains("Id") && type.ToString("Id") != ""
                                ? dao.Get(type.ToGuid("Id"))
                                : new InfoType(type.ToString("Name"));

            info.Name = type.ToString("Name");
            info.Comment = type.ToString("Comment");
            if (type.Contains("ParentId") && type.ToString("ParentId").Length != 0)
            {
                var parent = dao.Get(type.ToGuid("ParentId"));
                if (parent != null)
                {
                    parent.Add(info);
                }
            }
            dao.SaveOrUpdate(info);
            var result = new ReturnResult("保存成功", true);
            result.Data.Add("Id", info.Id);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Get()
        {
            var id = new Guid(Request.QueryString["id"]);
            if (id == Guid.Empty)
                return Json(new ReturnResult("", false), JsonRequestBehavior.AllowGet);


            InfoType result = OrnamentContext.Current.MessageManager.Factory.InfoTypeDao.Get(id);
            InfoType parent = result.Parent;
            return Json(new
                            {
                                result.Id,
                                result.Name,
                                result.Comment,
                                ParentName = parent != null ? parent.Name : "无父分类",
                                ParentId = parent != null ? parent.Id : Guid.Empty
                            },
                        JsonRequestBehavior.AllowGet);
        }
    }
}